<!DOCTYPE html>
<html xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Course List</title>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link href="style1.css" rel="stylesheet">
</head>
<body>

<div id="app">
    <h1>课程列表</h1>
    <button v-on:click="preAdd">添加课程</button>
    <table border="1" width="100%">
        <tr>
            <th>序号</th>
            <th>课程编号</th>
            <th>课程名称</th>
            <th>学院</th>
            <th>操作</th>
        </tr>
        <tr v-for="(item,index) in courses">
            <td>{{index + 1}}</td>
            <td>{{item.code}}</td>
            <td>{{item.name}}</td>
            <td>{{item.college?.name}}</td>
            <td>
                <button v-on:click="preEdit(index)">编辑</button>
                <button v-on:click="delCourse(item.id)">删除</button>
            </td>
        </tr>
    </table>

    <!-- 课程信息对话框 -->
    <dialog ref="dialog">
        <h3 align="center">{{editing ? 'Edit' : 'Add'}} course</h3>
        <table width="100%">
            <tr>
                <td>Code</td>
                <td><input type="text" v-model="editedCourse.code" placeholder="Input code of course"></td>
            </tr>
            <tr>
                <td>Name</td>
                <td><input type="text" v-model="editedCourse.name" placeholder="Input name of course"></td>
            </tr>
            <tr>
                <td>College</td>
                <td>
                    <select v-model="collegeId" style="width:100%;">
                        <option value="">Select college</option>
                        <option v-for="item in colleges" v-bind:value="item.id">{{item.name}}</option>
                    </select>
                </td>
            </tr>
        </table>
        <div class="action">
            <button v-on:click="this.editing=false;this.$refs.dialog.close()">cancel</button>
            <button v-if="editing" v-on:click="editCourse">Update</button>
            <button v-else v-on:click="addCourse">Save</button>
        </div>
    </dialog>

</div>
</body>
<script>
    const app = {
        data() {
            return {// editedCourse数据对象用来和各输入框双向绑定
                // 编辑状态
                editing: false, // editedCourse数据对象用来和各输入框双向绑定
                editedCourse: {
                    code: null,
                    name: null
                },
                courses: [], // 课程列表数据对象
                errorMsg: '',// 用于存储错误信息
                collegeId: null, // 新增或更改课程时选取的学院id
                colleges: []
            }
        },
        mounted() { //页面加载成功事件
            this.loadCourses();
            this.loadColleges();

        },
        methods: {// 读取课程函数
            loadCourses() {
                axios.get("/course/course").then(res => {//res 是返回对象
                    this.courses = res.data;
                }).catch(err => {
                    alert(err);
                });
            },
            loadColleges() {
                axios.get("/college/college").then(res => {
                    this.colleges = res.data;
                }).catch(err => {
                    alert(err);
                });
            },

            // 弹出“增加课程对话框”前处理
            preAdd() {
                // 新增课程前，课程信息置空
                this.editedCourse = {id: null, name: null};
                this.collegeId = null;
                this.editing = false;
                // 显示对话框
                this.$refs.dialog.showModal();
            },
            //“添加课程”函数
            addCourse() {
                // 提交到后端之前，先处理editedCourse的嵌入college的值，只需要传college的id即可
                if (this.collegeId) {
                    this.editedCourse.college = {id: this.collegeId};
                }
                axios.post('/course/course', this.editedCourse).then(res => {
                    this.loadCourses(); // 刷新课程列表
                    this.dialog = false; // 关闭对话框
                }).catch(err => {
                    let msg = err?.response?.data?.message || err.message || err;
                    alert(msg);
                });
            },
            // 删除课程函数
            delCourse(id) {
                axios.delete('/course/course/' + id).then(res => {
                    this.loadCourses();
                    alert(res.data);
                }).catch(err => {
                    alert('网络请求异常，请重试!');
                });
            },
            preEdit(index) {
                // 复制指定位置的课程到待编辑课程（因为this.editedCourse和对话框输入项绑定的）
                this.editedCourse = {
                    id: this.courses[index].id,
                    code: this.courses[index].code,
                    name: this.courses[index].name
                }
                // 设置学院下拉框为选中课程的学院id
                this.collegeId = this.courses[index].college?.id || null;
                this.editing = true; // 修改标志
                this.$refs.dialog.showModal(); // 弹出对话框
            },
            // 修改课程
            editCourse() {
                // 提交到后端之前，先处理editedCourse的嵌入college的值，值需要串college的id即可
                if (this.collegeId && this.collegeId != 'null') {
                    this.editedCourse.college = {id: this.collegeId};
                }
                axios.put('/course/course/' + this.editedCourse.id
                    + '?code=' + this.editedCourse.code
                    + '&name=' + this.editedCourse.name
                    + '&collegeId=' + this.collegeId
                ).then(res => {
                        if (res.data) {
                            this.loadCourses(); //当修改成功，刷新页面
                            this.editing = false;
                            this.$refs.dialog.close();
                        } else {
                            alert('修改课程《' + this.editedCourse.name + '》失败');
                            this.editing = false;
                            this.$refs.dialog.close();
                        }
                    }
                ).catch(err => {
                    console.error(err);
                    this.editing = false;
                    this.$refs.dialog.close();
                });
            },
        }
    }

    // 建立 Vue App 对象，并装载 <div id="app"></div> 元素为视图模板
    Vue.createApp(app).mount('#app')
</script>
</html>